package com.bo.rabbit.exception;

import com.sun.deploy.util.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.List;

/**
 * @program rabbit
 * @Description 全局异常处理器
 * @Author Diviner
 * @Date 2024/03/26 10:44
 * @Version 1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    //返回异常
    @ExceptionHandler(RabbitException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultException customException(RabbitException e){
        String errMessage = e.getErrMessage();
        return new ResultException(errMessage);
    }
    //全局异常处理器
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultException exception(Exception e){
        String message = e.getMessage();
        ResultException resultException = new ResultException(CommonError.UNKNOW_ERROR.getErrMessage());
        return resultException;
    }
    //方法参数异常处理器
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultException MethodArgumentNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> errorsList = bindingResult.getFieldErrors();
        errorsList.stream().forEach(item->{
            errorsList.add(item);
        });
        String errorMessage = StringUtils.join(errorsList, ",");
        ResultException resultException = new ResultException(errorMessage);
        return resultException;
    }
}
